app.push(function(){
    var Product = function(){
        var product = false;
        var productData = false;
        var getDataMode = 'get';
        var currentShop = 0;
        this.init = function(url){
            url = app.cloneArray(url || app.currentUrl);
            if(url[1] == 'add'){
                url[1] = 'edit';
                currentShop = url[2] + '';
                url[2] = false;
            }
            if(this[url[1]])this[url[1]](url);
            else this.showData(url[1]);
        }
        this.showData = function(id){
            mlhAPI.product.get(
            {
                id: id,
                callback: function(data){
                    app.leftMenu.hide();
                    app.main.unmask();
                    if(data['result'] == 'success'){
                        app.topMenu.breadcrumbList[1] = ['Список продуктов','#product/list/' + data.data.element.shop];
                        app.topMenu.breadcrumbList[2] = [data.data.element.title,'#product/' + data.data.element.product_id];
                        app.topMenu.buildBreadcrumb();
                        var paramsData = [];
                        $(data.data.element.param_data).each(function(){
                            paramsData[this.param_id] = this.small_value || this.long_value;
                        });
                        var extendFunctions = {
                            getTPL: function(type){
                                return 'param_show_field_type_' + type;
                            },
                            list: function(list){
                                var ret = [];
                                $(list.split(',')).each(function(){
                                    ret.push($.trim(this));
                                });
                                return ret;
                            }
                        };
                        $(data.data.element.params).each(function(){
                            this['currentValue'] = paramsData[this.param_id];
                            this['getTPL'] = extendFunctions.getTPL;
                            this['list'] = extendFunctions.list;
                        });
                        data.data.element['tags_count'] = data.data.element.tags.length;
                        console.log(data.data.element);
        				$.tmpl( 'product_content', data.data.element).prependTo(app.elements.general_content.html(''));
                        app.decorate.imageGallery(app.elements.general_content.find('[rel=productImages]'),data.data.element.image,data.data.element.image_id);
        				app.elements['comments'] = app.elements.general_content.find('#comments');
        				mlhAPI.product.getComments(
                        {
                            id: data.data.element.product_id,
                            callback: app.comments.showComments
                        });
                        app.decorate.setEvents(app.elements.general_content);
                    }
                }
            })
        }
        this.edit = function(url){
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            product = url[2] ? url[2] : false;
            if(!product){
                this.build({});
                app.main.unmask();
                app.leftMenu.setEditProductLeftMenu(product,currentShop);
            }else{
                mlhAPI.get({
                    c: 'product',
                    v: 'display',
                    id: product,
                    requestType: 'get_nc'
                },function(data){
                    console.log("Product data", data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    data.data.element['tags_count'] = data.data.element.tags.length;
                    currentShop = data.data.element['shop'];
                    productData = data.data.element;
                    this_.build(data.data.element);
                    app.topMenu.breadcrumbList[1] = ['Список продуктов','#product/list/' + currentShop];
                    app.topMenu.breadcrumbList[2] = [data.data.element['title'],'#product/edit/' + product];
                    app.topMenu.buildBreadcrumb();
                    app.leftMenu.setEditProductLeftMenu(product,currentShop);
                });
            }
            if(product){
                $('#productEditForm button[type=submit]').text('Редактировать продукт');
            }
            
        }
        this.build = function(data){
            jQuery.extend(data, {
                editMode: product!=false
            });
            var el = $.tmpl('edit_product',data);
            el.prependTo(app.elements.general_content.html(''));
            app.decorate.validateRule($('#productEditForm input, #productEditForm textarea, #productEditForm select'),
            {
                success: ' ',
                endValid: function(error){
                    if(!error){
                        $('#productEditForm .control-group').each(function(){
                            if($(this).hasClass('error')) error = true;
                            $(this).find('*[rel=req]').each(function(){
                                var value = $(this).val();
                                if(this.tagName=='SELECT' && (value==0 || value == '0') )value = false;
                                if(!value) error = true;
                            });
                        });
                    }
                    $('#productEditForm button[type=submit]').attr('class', !error ? 'btn btn-success' : 'btn btn-warning');
                    if(!error){
                       $('#productEditForm').find('.alert-info').show();
                       $('#productEditForm').find('.alert[data-type=error]').hide();
                    }
                }
            });

            var newImage = false;
            var getImages = function(){
                var data = [];
                $('div[rel=image] input[name=images]').each(function(){
                    var el = $(this);
                    var img = el.prev();
                    var filename = img.attr('src').split('/');
                    data.push({
                        filename: filename.pop(),
                        image_id: el.val(),
                        title: img.attr('title'),
                        size: img.attr('data-size')
                    })
                });
                return data.length ? data : false;
            }
            
            var onComplete = function(){
                var titleImageId = $('#productEditForm input[name=image_id]');
                var el = $('#upload_image_' + titleImageId.val());
                if(el.length)el.attr('class','active'); 
                else {
                    var firstElement = $('div.uploaded_image:first');
                    if(firstElement.length > 0) {
                        titleImageId.val(firstElement.find('input:first').val());
                        firstElement.find('div[rel=status]:first').attr('class','active'); 
                    }
                    else {
                        titleImageId.val(0);
                    }
                }
                $('div.uploaded_image').click(function(){
                    var value = $(this).find('input:first').val();
                    $('div.uploaded_image div[rel=status]').attr('class','');
                    $('#upload_image_' + value).attr('class','active');
                    titleImageId.val(value);
                });
                newImage = true;
            }
            $('#productEditForm input[name=image_id]').val(data.image_id);
            onComplete();
            app.decorate.imageForm($('#productEditForm'), getImages, newImage, 10, {
                onFullComplete: onComplete
            });
            $('#productEditForm form').submit(function(){
                if($('#productEditForm button[type=submit]').hasClass('btn-warning')){
                    $('#productEditForm').find('.alert[data-type=error]').addClass('alert-error').text("Заполните все необходимые поля").show();
                    $('#productEditForm').find('.alert-info').hide();
                    $('#productEditForm').find('*[rel=req]').each(function(){
                        var value = $(this).val();
                        if(this.tagName=='SELECT' && (value==0 || value == '0') )value = false;
                        if(!value) {
                            $(this).parents('.control-group:first')
                                .attr('class','row control-group warning span12 no_left_margin')
                                .find('.alert:first').text('Это поле обязательно надо заполнить').show();
                            
                        }
                    });
                    return false;
                }
                var formData = {
                    callback: function(data){
                        console.log(data);
                        if(data.data['errors'] || data.data['error'] || data.result == "error"){
                            var text = "";
                            if(data.data['errors']){
                                for(var k in data.data.errors){
                                    if(k=='email')$('#productEditForm input[name=email]').parents('.control-group:first').attr('class','row control-group error');
                                    text += "<div>" + data.data.errors[k] +"</div>";
                                }
                            }else{
                                text += "<div>" + data.data['error'] +"</div>";
                            }
                            $('#productEditForm').find('.alert[data-type=error]').addClass('alert-error').html(text).show();
                            $('#productEditForm').find('.alert-info').hide();
                            $('#productEditForm button[type=submit]').attr('class', 'btn btn-warning');
                        }else{
                            $('#productEditForm').find('.alert[data-type=error]').hide();
                            //$('#productEditForm').find('.alert-info').html(product ? 'Вы успешно отредактировали продукт' : 'Вы успешно создали продукт').show();
                            $('#productEditForm button[type=submit]').attr('class', 'btn btn-success');
                            app.static.success({description:(product ? 'Вы успешно отредактировали товар' : 'Вы успешно создали товар')})
                            getDataMode = 'get_rc';
                            app.go('#product/list/' + currentShop);
                        }
                    }
                }
                if(product) formData['product_id'] = product;
                var sData = $(this).serializeArray();
                for(var i = 0; i < sData.length; i++) {
                    formData[sData[i].name] = sData[i].value;
                }
                var images = [];
                $(this).find('input[name=images]').each(function(){images.push($(this).val())});
                formData['model'] = 'product';
                formData['images'] = images.join(',');
                formData['newImage'] = newImage ? 1 : 0;
                formData['tag_id'] = $('#productEditForm [name=tags]').getAsJSON();
                formData['shop'] = currentShop;
                console.log(formData);
                mlhAPI.product.set(formData);
                return false;
            });
           mlhAPI.category.getList({
               model:'product',
               shop_name: currentShop,
               callback: function(list){
                    console.log("Category List", list);
                    if(list.result=='error'){
                        return;
                    }
                    delete list.data['log'];
                    var select = $('#productEditForm select[name=category_id]');
                    app.decorate.buildSelectIttems(select, {
                        list: list.data,
                        key: 'category_id',
                        active: data['category_id'],
                        multilevelKey: 'child'
                    });
                    select.change(function(){
                        setParams(select.val());
                    });
                    setParams(data['category_id']);
                }
           });
           setTimeout(function(){
                $('#productEditForm [name=tags]').tagsInput(
                {
                    width:'auto',
                    defaultText: '+ добавить',
                    autocomplete_url:'http://'+location.host+'/api.php?h=tag&v=autocomplete'
                });
           },300);
        }
        this.list = function(){
            var productContainer = false;
            var this_ = this;
            if(app.user_info.user_logined!=true){
                console.log('Только для зарегистрированных');
                app.static.registered_only();
                return;
            }
            if(!app.currentUrl[2]){
                app.go('#shop/list');
                return;
            }
            currentShop = app.currentUrl[2];
            app.topMenu.breadcrumbList[1] = ['Список продуктов','#product/list/'+currentShop];
            app.topMenu.breadcrumbList[2] = false;
            app.topMenu.buildBreadcrumb();
            app.leftMenu.setEditShopLeftMenu(currentShop);
            var el = $.tmpl('manage_product_list', 
            {
                show_select: app.user_info.user_product > 1,
                shop: currentShop
            });
            productContainer = $(el).find('[rel=product_list]:first');
            el.prependTo(app.elements.general_content.html(''));
            mlhAPI.product.getListByShop({
                shop: currentShop,
                requestType: getDataMode,
                callback: function(data){
                    console.log(data);
                    app.main.unmask();
                    if(data.result=='error'){
                        return;
                    }
                    productContainer.html(data.data.info.length ? '' : 'Нет продуктов');
                    for(var i in data.data.info){
                        var info = data.data.info[i];
                        info['tags_count'] = info.tags.length;
                        var el = $.tmpl('manage_product_element', info);
                        el.find('.tags .koma:last').hide();
                        el.prependTo(productContainer);
                        app.decorate.setEvents(el);
                    }
                }
            });
            getDataMode = 'get';
        }
        var setParams = function(category_id){
            var paramContainer = $('#product_params_list').html(' ');
            if(category_id>0){
                mlhAPI.param.getList({
                    category_id: category_id,
                    callback: function(data){
                        console.log(data);
                        if(data.result=='error'){
                            return;
                        }
                        var el = $.tmpl('param_edit_field', data.data.list, {
                            getTPL: function(type){
                                return 'param_edit_field_type_' + type;
                            },
                            list: function(list){
                                var ret = [];
                                $(list.split(',')).each(function(){
                                    ret.push($.trim(this));
                                });
                                return ret;
                            }
                        });
                        app.decorate.setEvents(el);
                        el.appendTo(paramContainer);
                        if(productData && productData['category_id'] == category_id){
                            $(productData.param_data).each(function(){
                                var el = $("#product_params_list [name='param_[" + this.param_id + "]']");
                                if(el[0].tagName == "INPUT" && el[0].type=="checkbox" && (this.small_value || this.long_value)) {
                                    el.attr('checked','checked');
                                    return;
                                }
                                el.val(this.small_value || this.long_value);
                            });
                        }
                        $('#product_params').show();
                    }
                });
            }
            if(category_id>0)$('#product_params').show();
            else $('#product_params').hide();
        }
    }
    app['product'] = new Product();
});